﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Hartley.ApplicationLogic;
using Hartley.DTOs;
using System.Drawing;
namespace WebApplication1
{
    public partial class AddCommittee : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            

        }

        protected void btnCommitteeSubmit_Click(object sender, EventArgs e)
        {
             DateTime startDate = DateTime.MinValue; 
             DateTime endDate = DateTime.MinValue;
             int startYear = 0;
             int endYear=0;

            bool convertableToStartDate = DateTime.TryParse(txtCommitteeStartDate.Text.ToString(),out startDate);
            bool convertableToEndDate = DateTime.TryParse(txtCommitteeEndDate.Text.ToString(),out endDate);

            bool convertabeToIntegerStartYr=false;
            bool convertabeToIntegerEndYr=false;

            if(!convertableToStartDate)
            {
                convertabeToIntegerStartYr = Int32.TryParse(txtCommitteeStartDate.Text.ToString(),out startYear);
                if(convertabeToIntegerStartYr && startYear.ToString().Length == 4)
                {
                    startDate =Convert.ToDateTime(startYear + "-01-01");
                   
                }
                else
                {

                    //Response.Redirect("AddCommittee.aspx?Entered Committee Start Year is not in valid format");
                    lblAddCommitteeMsg.Text = "Entered Committee Start Year is not in valid format";
                    return;
                }
            }

            if(!convertableToEndDate)
            {

                convertabeToIntegerEndYr = Int32.TryParse(txtCommitteeEndDate.Text.ToString(),out endYear);

                 if(convertabeToIntegerEndYr && endYear.ToString().Length == 4)
                {
                     //If the enter the same end yr as start yr thn keep as it's otherwise reduce one yr eg : start 01-01-1990 end 31-12-1991
                    if (startYear == endYear)
                    {
                        endDate = Convert.ToDateTime(endYear + "/12/31");
                    }
                    else if ((endYear - startYear) < 5)
                    {
                        endDate = Convert.ToDateTime(endYear - 1 + "/12/31");
                    }
                    else
                    {
                        //Response.Redirect("AddCommittee.aspx?Entered Committee Start Year & End Year are too differ");
                        lblAddCommitteeMsg.Text = "Entered Committee Start Year & End Year are too differ  or end date is less than start year";
                        return;
                    }
                   
                }
                else
                {

                    //Response.Redirect("AddCommittee.aspx?Entered Committee End Year is not in valid format");
                     lblAddCommitteeMsg.Text = "Entered Committee End Year is not in valid format";
                     return;

                }
            
            }



            try
            {

                if ((endDate.Year - startDate.Year) > 5 || (endDate.Year - startDate.Year) < 0)
                {

                    //Response.Redirect("AddCommittee.aspx?Entered Committee Start Year & End Year are too differ");
                    lblAddCommitteeMsg.Text = "Entered Committee Start Year & End Year are too differ or end date is less than start year";
                    return;
                }

                String startYr = txtCommitteeStartDate.Text.ToString().Substring((txtCommitteeStartDate.Text.ToString().LastIndexOf("/") + 1), 4);
                String EndYr = txtCommitteeEndDate.Text.ToString().Substring((txtCommitteeEndDate.Text.ToString().LastIndexOf("/") + 1), 4);
                //String startYr = txtCommitteeStartDate.Text.ToString().Substring((txtCommitteeStartDate.Text.ToString().LastIndexOf("/") + 1), 4);
                //String EndYr = txtCommitteeEndDate.Text.ToString().Substring((txtCommitteeEndDate.Text.ToString().LastIndexOf("/") + 1), 4);
                //String startYr=Convert.ToDateTime(txtCommitteeStartDate.Text.ToString)
                try
                {

                    CommitteeDTO committeeDTO = new CommitteeDTO
                    {
                        CommitteeId = Guid.NewGuid(),
                        Title = "Executive Committee Of J/HartleyCollege's Colombo PPA for the Year of  " + EndYr + "/" + startYr,
                        StartDate = Convert.ToDateTime(txtCommitteeStartDate.Text),
                        EndDate = Convert.ToDateTime(txtCommitteeEndDate.Text),
                        Description = txtCommitteeDescription.Text,
                        CommitteePhotoName = fuAddCommitteePhoto.FileName,
                        CommitteePhotoPath = "CommitteePhotos" + "\\" + fuAddCommitteePhoto.FileName,
                        //ModifiedBy = "Tharsan",
                        ModifiedTime = DateTime.Now
                    };
                    MemberAL memberAL = new MemberAL();
                    string result = memberAL.saveCommittee(committeeDTO);


                    if (result == "Saved")
                    {
                        lblAddCommitteeMsg.Text = "Committee Details added Successfully";
                        txtCommitteeStartDate.Text = "";
                        txtCommitteeEndDate.Text = "";
                        txtCommitteeDescription.Text = "";

                    }
                    else if (result == "Updated")
                    {
                        lblAddCommitteeMsg.Text = "Committee Details updated Successfully";
                        txtCommitteeStartDate.Text = "";
                        txtCommitteeEndDate.Text = "";
                        txtCommitteeDescription.Text = "";
                    }
                    else if (result == "AlreadyExists")
                    {
                        lblAddCommitteeMsg.Text = "The Committee name added by you is already exists";
                        txtCommitteeStartDate.Text = "";
                        txtCommitteeEndDate.Text = "";
                        txtCommitteeDescription.Text = "";
                    }
                    else
                    {
                        lblAddCommitteeMsg.Text = "Your data cannot be added";
                        txtCommitteeStartDate.Text = "";
                        txtCommitteeEndDate.Text = "";
                        txtCommitteeDescription.Text = "";
                    }

                    if ((fuAddCommitteePhoto.PostedFile != null) && (fuAddCommitteePhoto.PostedFile.FileName != ""))
                    {
                        string sSavePath;
                        string sThumbExtension;
                        int intThumbWidth;
                        int intThumbHeight;

                        // Set constant values

                        sSavePath = "CommitteePhotos\\";
                        sThumbExtension = "_thumb";
                        intThumbWidth = 160;
                        intThumbHeight = 120;
                        string fileName = System.IO.Path.GetFileName(fuAddCommitteePhoto.PostedFile.FileName);
                        string saveLocation = Server.MapPath(sSavePath) + fileName;
                        HttpPostedFile myFile = fuAddCommitteePhoto.PostedFile;
                        int nFileLen = myFile.ContentLength;


                        try
                        {
                            if (fuAddCommitteePhoto.PostedFile.ContentLength > 5120) // 5120 KB means 5MB
                            {

                                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);

                            }

                            else
                            {
                                // Check file extension (must be JPG)

                                if (System.IO.Path.GetExtension(fuAddCommitteePhoto.FileName).ToLower() != ".jpg")
                                {
                                    lblAddCommitteeMsg.Text = "The file must have an extension of JPG";
                                    return;
                                }

                                // Read file into a data stream

                                byte[] myData = new Byte[nFileLen];
                                myFile.InputStream.Read(myData, 0, nFileLen);

                                // Make sure a duplicate file doesn�t exist.  If it does, keep on appending an 

                                // incremental numeric until it is unique

                                string sFilename = System.IO.Path.GetFileName(myFile.FileName);
                                int file_append = 0;
                                while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
                                {
                                    file_append++;
                                    sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                                     + file_append.ToString() + ".jpg";
                                }

                                // Save the stream to disk

                                System.IO.FileStream newFile
                                        = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
                                                                   System.IO.FileMode.Create);
                                newFile.Write(myData, 0, myData.Length);
                                newFile.Close();

                                // Check whether the file is really a JPEG by opening it

                                System.Drawing.Image.GetThumbnailImageAbort myCallBack =
                                               new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                                Bitmap myBitmap;

                                fuAddCommitteePhoto.PostedFile.SaveAs(saveLocation);
                                //Response.Write("The File has been uploaded successfully");

                               

                            }
                        }
                        catch (Exception ex)
                        {
                            Response.Write("Error occured while uploading the files...!!!" + ex);
                        }

                    }


                    else
                    {
                        Response.Write("Please select a file to upload.");

                    }

                }
                catch (Exception ee)
                {
                    lblAddCommitteeMsg.Text = "There is an exception occured while inserting the Committee detail" + ee.ToString();
                }
            }
            catch (Exception ee)
            {
                lblAddCommitteeMsg.Text = "There is an exception occured while inserting the Committee detail11" + ee.ToString();
            }
        }

            public bool ThumbnailCallback()
              {
                  return false;
              }
        }
              
             
            }

     
            
      